/**
 * 超长对象拆解
 * @param str
 * @returns
 */
const analyseObj = (str) => {
  // 循环处理
  let buffer = {
    c: {},
    p: {},
  };
  const task = [];
  const pipeJson = JSON.parse(str);
  for (let pk of Object.keys(pipeJson)) {
    for (let key of Object.keys(pipeJson[pk])) {
      buffer[pk] = {
        ...buffer[pk],
        [key]: pipeJson[pk][key],
      };
      if (JSON.stringify(buffer).length >= 1000) {
        task.push(buffer);
        buffer = {
          c: {},
          p: {},
        };
      }
    }
  }
  task.push(buffer);
  console.log(`task: analyseObj 拆解为 ${task.length} 个任务`);
  return task;
};

/**
 * 拆解对象合并
 * @param arr
 * @returns
 */
const mergeObj = (arr) => {
  let buffer = {
    c: {},
    p: {},
  };
  for (let pipeJson of arr) {
    for (let pk of Object.keys(pipeJson)) {
      for (let key of Object.keys(pipeJson[pk])) {
        let tmp = key;
        if (buffer[pk]?.[key]) {
          const num = key.match(/.*?(\d+)$/)?.[1] || 0;
          tmp += `_${Number(num) + 1}`;
        }
        buffer[pk] = {
          ...buffer[pk],
          [tmp]: pipeJson[pk][key],
        };
      }
    }
  }
  return buffer;
};
module.exports = {
  analyseObj,
  mergeObj,
};
